/**
 * 用户相关方法
 *
 * @format
 */

import { BaseDao } from '../../sdk'
import BaseService from './base.service'
import { JWT_DB, REGISTER_DB_NAME, USER_DB_NAME } from '../../db'
import { initCustomUserWhenLogin, updateUserWhenLogin } from '../../customUser'
import { getToday, formatUpdateUserProjection } from '../../utils'
import { isNewVip } from '../../utils/common/userUpdate'
import { formatUserNick, formatUpdatedDataByProjection } from '../../utils/common/format'
import { setNewFollowUserData, setNewVipUserData } from '../../utils/common/userUpdate'
import { getShopVip, formatVipCbUrl } from '../../utils/common/vip'
import { get } from 'mpath'
import { merge } from 'lodash'
import { sendWildWoodRequest } from '../../utils/common/wildwood'
import { TRACK_EVENTS, SELLER_SHOP_CONFIG, OSS_URL, APPKEY, APP_KEY, BASE_CONFIG } from '../../constants'
import { sendQimenRequest } from '../../utils/common/qimen'

import * as aesUtil from '../../utils/common/aesUtil'
import dayjs = require('dayjs')

class UserService extends BaseService {
  userdao: IBaseDao
  jwtdao: IBaseDao
  registerdao: IBaseDao
  constructor(context: IContext<IParams>) {
    super(context)
    this.userdao = new BaseDao(context, USER_DB_NAME)
    this.jwtdao = new BaseDao(context, JWT_DB)
    this.registerdao = new BaseDao(context, REGISTER_DB_NAME)
  }

  //打通用户信息
  async registerInfo(earlybird_id:string, shop_id:string) {
    //获取加密信息
    // const version = JSON.stringify({
    //   third_party_open_id: this.context.openId,
    //   shop_id,
    //   seller_id: SELLER_SHOP_CONFIG[shop_id],
    //   appkey: APP_KEY,
    //   timestamp: dayjs().format()
    // })

    // const jwtInfo: any = await this.jwtdao.findOne({ name: 'jwt' })
    // const { httpKey } = jwtInfo
    // 调用奇门得key，在registerInfo调用
    // const httpKey =
    //   'UrugZaHXhJ0qjt7TXQzABLe6gAv83ufyLbBAs8KfIrlsdOPKWeSXb5LsOEQUMmIT2mBlPWObNkjuap4YmILezteY47nKnLXnHhd'
    // const encryptContent = aesUtil.encrypt(version, httpKey)
    const configInfo: IConfig = await this.getEnvConfig()
    const { API_URL_LIST } = configInfo

    //获取头像参数
    //获取头像参数
    const body = {
      open_id: this.context.openId
    }
    const qimenRealPath = API_URL_LIST.REGISTER.path
    return await sendQimenRequest(this.context, qimenRealPath, body, SELLER_SHOP_CONFIG[shop_id],+shop_id)
  }

  

  //埋点接口
  async addPromise(activityInfo: IActivityInfo, userNick: string, event: string, Properties: any = {}) {
    const { version, platform, isTask = false } = this.context.data
    let body = {
      userId: userNick,
      shopId: activityInfo.shopId,
      anonymousId: userNick,
      name: 'PILE',
      event,
      env: this.context.env === 'online' ? 'production' : 'test',
      type: 'track',
      context: {
        library: {
          name: 'segment-wildwoodmg',
          version: '0.0.1'
        },
        device: {
          type: platform
        },
        app: {
          name: 'PILE',
          version
        },
        referrer: {
          type: isTask ? 'wildwoodmp' : 'member center'
        }
      },
      properties: {
        classification: 'experience',
        eventName: event,
        eventType: 'track',
        tmallShopId: activityInfo.shopId,
        name: 'PILE',
        userId: userNick,
        traceId: this.context.data.traceId,
        // tier: userInfo?.member?.tier || 0,
        ...Properties
      }
    }
    console.log(body, 'body----------')
    const { API_URL_LIST } = BASE_CONFIG
    return await sendWildWoodRequest(this.context, API_URL_LIST.DATA_TRACK, event, body)
  }

  async addTrackRequest(activityInfo: IActivityInfo, userNick: string, event: string, Properties: any = {}) {
    const apiPromise = new Promise(resolve => {
      resolve(this.addPromise(activityInfo, userNick, event, Properties))
    })
    const defaultPromise = new Promise(resolve => {
      setTimeout(() => {
        resolve(JSON.stringify({ success: true }))
      }, 100)
    })

    const result = await Promise.race([apiPromise, defaultPromise])
    return result
  }

  /**
   * 查询会员信息
   * @param context
   * @param activityInfo
   */
  async getUserVipInfo(context: IContext<IParams>, activityInfo: IActivityInfo) {
    const { shopId, onlineUrl = '', _id } = activityInfo

    const callbackurl = this.formatVipCbUrl(onlineUrl, _id)
    const sellerId = SELLER_SHOP_CONFIG[shopId] || '890482188'
    const totalUrl = this.generateVipUrl(callbackurl, sellerId)
    return {
      isVip: context?.data?.isVip,
      url: totalUrl
    }
  }

  // 生成会员链接
  generateVipUrl(callbackUrl: string, sellerId: string) {
    return `https://market.m.taobao.com/app/sj/member-center-rax/pages/pages_index_index?wh_weex=true&sellerId=${sellerId}&extraInfo=${encodeURIComponent(
      JSON.stringify({ source: 'isvapp' })
    )}&callbackUrl=${encodeURIComponent(callbackUrl)}`
  }

  // 格式化Vip回调地址
  formatVipCbUrl(vipCallBackUrl: string, activityId: string) {
    // 拼接回调参数
    let query = `activityId=${activityId}&isTask=${this.context.data.isTask || false}&fromVipCenter=1`
    let pages = `pages/loadingScene/loadingScene`

    let callbackUrl: string = `${vipCallBackUrl}&query=${encodeURIComponent(query)}&page=${encodeURIComponent(pages)}`
    return callbackUrl
  }
}

export default UserService
